<template>
  <PageWrapper title="编辑个人信息">
    <div class="py-8 bg-white flex flex-col justify-center items-center">
      <BasicForm @register="register" />
      <div class="flex justify-center">
        <a-button class="!ml-4" type="primary" @click="handleSubmit"> 提交 </a-button>
      </div>
    </div>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { onMounted, ref } from 'vue';
  import { PageWrapper } from '@/components/Page';
  import { BasicForm, useForm } from '@/components/Form';
  import { getMe, updateUser } from '@/api/user';

  import { formSchema } from './data';
  import { useMessage } from '@/hooks/web/useMessage';

  const { notification } = useMessage();

  const [register, { validate, resetFields, setFieldsValue }] = useForm({
    size: 'large',
    baseColProps: { span: 24 },
    labelWidth: 100,
    showActionButtonGroup: false,
    schemas: formSchema,
  });

  const id = ref();

  onMounted(async () => {
    resetFields();
    const me = await getMe();
    id.value = me.id;
    setFieldsValue({...me});
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      await updateUser(id.value, values).then(() => {
        notification.success({
          message: '',
          description: '提交成功',
          duration: 2,
        });
      }).catch(error => {
        notification.error({
          message: '',
          description: '提交失败',
          duration: 2,
        });
      });
    } catch (error) {
      console.error(error);
    }
  }
</script>